//1. 导入 express
const express = require('express');
const { query } = require("../mysql")
const jwt = require("../util/JWTConfig")

const resultClass = require("../dto/result")
//2. 创建路由器对象
const router = express.Router();

//3. 在 router 对象身上添加路由
router.get('/', async (req, res) => {
    const sql = 'select * from `sys_user`'
    const result = await query(sql)
    const resultData = new resultClass(0, result)
    res.send(resultData);
})

router.get('/login', async (req, res) => {
    let userInfo = {}
    if (req.userInfo?.username) {
        userInfo = req.userInfo
    } else {
        userInfo = req.query
    }
    console.log(req.query);
    const sql = `select * from sys_user where username='${userInfo.username}' && password='${userInfo.password}'`
    const result = await query(sql)
    let code = 0
    if (!result || result.length === 0) {
        code = 200
        const resultData = new resultClass(code, result[0])
        res.send(resultData);
        return
    }
    console.log(sql, "查询结果----------------", result);
    let { username, password } = result[0] // 提取用户信息
    const token = jwt.signToken({ username, password }) // 根据用户信息生产token
    result[0].token = token
    const resultData = new resultClass(code, result[0])
    res.send(resultData);
});

// 注册用户
// 注册用户
router.post('/register', async (req, res) => {
    try {
        const userInfo = req.body;

        // 打印调试信息
        console.log('register:', userInfo);

        // 验证输入
        if (!userInfo.username || !userInfo.password) {
            return res.status(400).send({
                code: 400,
                msg: '用户名或密码不能为空',
                data: null
            });
        }

        // 使用参数化查询防止 SQL 注入
        const sql = `INSERT INTO sys_user (username, password) VALUES ('${userInfo.username}', '${userInfo.password}')`;

        // 执行查询
        const result = await query(sql);

        // 返回成功响应
        res.send({
            code: 0,
            msg: '注册成功',
            data: result
        });
    } catch (error) {
        console.error('注册失败:', error);

        // 返回错误响应
        res.status(500).send({
            code: 500,
            msg: '服务器内部错误',
            data: null
        });
    }
});

//4. 暴露
module.exports = router;